<template>
  <div>
    <a-card
      :bordered="false"
      :body-style="{
               overflowY:'auto',
               overflowX:'hidden',
           }"
    >
      <a-tree
        :data="treeData"
        :field-names="{key:'id',title:'name'}"
        v-model:expanded-keys="expandedKeys"
        v-model:selected-keys="selectKeys"
        @select="(key,data)=>{handleDept(key,data)}"
      >
        <template #title="nodeData">
          <div
            :class="selectKeys && selectKeys.length >0 && selectKeys[0] == nodeData.id ? 'treeNode-selected' : ''"
          >{{ nodeData.name }}</div>
        </template>
      </a-tree>
    </a-card>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { treeDept } from '@/api/sys/dept';

// 加载按钮
const loading = ref(false);

const formRef = ref();

const emit = defineEmits({ onSearch: null });

const treeData = ref<any>([]);
const expandedKeys = ref<any>([]);
const selectKeys = ref([]);

// 获取部门数据
const fetchData = async () => {
  treeDept({}).then((res: any) => {
    if (res.data && res.data.length > 0) {
      let defaultExpandKeys = [0];
      for (let i = 0; i < res.data.length; i++) {
        defaultExpandKeys.push(res.data[i].id);
      }
      expandedKeys.value = defaultExpandKeys;
    } else {
      expandedKeys.value = [0];
    }
    treeData.value = res.data;
  });
};

// 部门搜索
const handleDept = (keys: any, data: any) => {
  selectKeys.value = keys;
  emit('onSearch', null, keys[0]);
};

// 重置已选部门
const initSelectKeys = () => {
  selectKeys.value = [];
};

// 抛出函数
defineExpose({
  initSelectKeys,
});

// 初始化操作
const initData = async () => {
  await fetchData();
};
initData();
</script>
